$(function() {
	prepareNewInfilPage();
})

/* This should ad a button to the page that will start all infiltrations at 10% */
function prepareNewInfilPage() {
	
	var planetID = $('input[type=hidden][name=planetid]').val();
	
	var allInfilButton = $( document.createElement('input') )
		.attr({
			type: 'button',
			value: 'Start ALL Infiltrations'
		})
		.css({
			display: 'block',
			marginTop: '10px'
		})
		.addClass('button')
		.insertAfter('select[name=infplanetid]')
	;
	
	var outputDiv = $( document.createElement('div') )
		.insertAfter( allInfilButton )
	;
	
	var infilCounter = 0;
	var infilCounterTreshold = 50;
	
	var infilAnotherPlanet = function() {
		var infPlanet = $('select[name=infplanetid] option:first');
		
		if( infilCounter >= infilCounterTreshold ) {
			outputDiv.append('<hr>You should probably leave it alone for a little while or you might get a 5 minute ban.<hr>');
			return;
		}
		
		if( !infPlanet.length ) {
			outputDiv.append('DONE!');
			allInfilButton.remove();
			$('select[name=infplanetid]').remove();
			$('input[name=newinfiltr]').remove();
			$('input[name=action]').val('Done');
			return;
		}
		
		var planetName = infPlanet.html().replace(/ - Civ\..*$/,'');
		
		if( planetName.match(/\[=H=\]$/) ) {
			outputDiv.append('Skipping ' + planetName + '! Cannot infil Hyps Prot.<br />');
			infPlanet.remove();
			infilAnotherPlanet();
			return;
		}
		
		outputDiv.append('infiltrating ' + planetName + ' at 10%');
		captchaAwareAjax({
			url: '/servlet/Planetinf',
			method: 'POST',
			data: {
				infplanetid: infPlanet.val(),
				newinfiltr: 'New infiltration',
				planetid: planetID,
				securitylevel: 10
			},
			success: function(resp, textStatus) {
				infilCounter++;
				var infilResult = resp.match(/[^><]*(?=<BR><BR><center><form action=Planetinf method=post>)/);
				if( !infilResult ) infilResult = ['Done!'];
				
				outputDiv.append(' - '+infilResult[0]+'<br />');
				infPlanet.remove();
				infilAnotherPlanet();
			}
		});
	}

	allInfilButton.on('click',function() {
		infilCounter = 0;
		infilAnotherPlanet();
	});
}